import java .io .*;
import java . security .*;

/**
 * KeyGen takes in a username and generates a random public key and private key for the user
 *   
 * @author Tom Napps, Andrew Gifford
 */
public class KeyGen {

	/**
	 * Main class that takes in the depth of encryption (5120, the seed for the key and the output
	 *   
	 * @param a[]
	 */
	public static void main ( String [] a) {
			if (a. length <3) {
				System .out . println (" Usage :");
				System .out . println (" java KeyPairFromSeed keySize seedForKey output ");
				return ;
			}
			int keySize = Integer.parseInt(a [0]);
			String seedForKey = a [1];
			String output = a[2];
			try {
				getKeys(seedForKey, keySize, output,"RSA"); // Use the RSA encryption algorithm
			} catch ( Exception e) {
				System.out.println(" Exception : "+e);
				return ;
			}
	}
	
	/**
	 * Writes the keys to .pub and .pri files for the new user
	 *   
	 *   @param seedForKey
	 *   @param keySize (512)
	 *   @param user The username
	 *   @param algorithm The algorithm used for encryption (RSA)
	 */
	public static void getKeys ( String seedForKey , int keySize , String user , String algorithm ) throws Exception {
		KeyPairGenerator kg = KeyPairGenerator.getInstance (algorithm);
		SecureRandom secureSeed = SecureRandom.getInstance("SHA1PRNG"); // Not just any
		// old random generator
		byte [] keyData = seedForKey.getBytes();
		secureSeed.setSeed(keyData);
		kg.initialize(keySize, secureSeed);
		KeyPair pair = kg. generateKeyPair ();
		PrivateKey priKey = pair.getPrivate();
		PublicKey pubKey = pair.getPublic();
		String fl = user +".pri";
		FileOutputStream out = new FileOutputStream (fl);
		byte[] ky = priKey.getEncoded();
		out.write(ky);
		out.close();
		fl = user +".pub";
		out = new FileOutputStream(fl);
		ky = pubKey.getEncoded();
		out.write(ky);
		out.close();
		
	}
}
